package com.nbjtjc.safe.service.sys;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.nbjtjc.safe.bean.MyPageInfo;
import com.nbjtjc.safe.bean.Page;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.sys.SysOptionMapper;
import com.nbjtjc.safe.model.sys.SysOption;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class SysOptionService {



    @Autowired
    private SysOptionMapper sysOptionMapper;

    public MyPageInfo<SysOption> find(Page page,SysOption sysOption) {
        PageHelper.startPage(page.getPageCurrent(),page.getPageSize());
        List<SysOption> options =null;
        MyPageInfo<SysOption> myPageInfo=null;
        try {
            Example example = new Example(SysOption.class);
            Example.Criteria criteria = example.createCriteria();
            if (ObjectUtil.isNotNull(sysOption) && ObjectUtil.isNotNull(sysOption.getName())) {
                criteria.andLike("name", '%'+sysOption.getName()+'%');
            }
            options = sysOptionMapper.selectByExample(example);
            myPageInfo=new MyPageInfo<>(options);
        } catch (Exception e) {
            e.printStackTrace();
            myPageInfo=new MyPageInfo<>();
            myPageInfo.setCode(400);
            myPageInfo.setMsg("查找失败,错误信息:"+e.getMessage());
        }
        return myPageInfo;
    }

    public Result<Boolean> delete(SysOption sysOption){
        int res = 0;
        Result<Boolean> result = new Result<>();
        res=sysOptionMapper.deleteByPrimaryKey(sysOption.getId());
        if(res==0){
            result.setFalse("删除失败");
        }
        return result;
    }

    public Result add(SysOption sysOption) {
        int res = 0;
        Result result = new Result<>();

        SysOption option=sysOptionMapper.selectOne(sysOption);
        if(option!=null){
            result.setFalse("该选项已经存在");
            return result;
        }
        if(ObjectUtil.isNull(sysOption)){
            result.setFalse("option不能为空");
            return result;
        }
        res=sysOptionMapper.insert(sysOption);
        if(res==0){
            result.setFalse("插入失败");
        }
        result.setData(sysOption);
        return result;
    }

    public Result update(SysOption sysOption) {
        int res = 0;
        Result result = new Result<>();
        if(ObjectUtil.isNull(sysOption)||ObjectUtil.isNull(sysOption))
        {
            result.setFalse("更新操作不能为空");
            return  result;
        }
        res=sysOptionMapper.updateByPrimaryKeySelective(sysOption);
        if(res==0){
            result.setFalse("更新失败");
            return result;
        }
        result.setData(sysOption);
        return result;
    }

}
